# 5_3 使用使用I2S播放音乐：播放sd卡wav
# https://learn.adafruit.com/adafruit-esp32-s3-tft-feather/i2s
"""
CircuitPython I2S WAV file playback.
Plays a WAV file on sd card.
"""
import board
import audiocore
import audiobusio
import digitalio

import busio
import storage
import adafruit_sdcard

import os
import sys
import time

print("start")
spi = board.SPI()
cs = digitalio.DigitalInOut(board.RX)

print("connect")
sdcard = adafruit_sdcard.SDCard(spi, cs)

print("VfsFat")
vfs = storage.VfsFat(sdcard)

print("mount")
storage.mount(vfs, "/sd")
print("mount ok")


'''
Board 3V to breakout VIN
Board GND to breakout GND
Board A0 to breakout BCLK
Board A1 to breakout LRC
Board A2 to breakout DIN
Board A3 to breakout GAIN
'''

I2S_BCLK = board.A0
I2S_LRC = board.A1
I2S_DIN = board.A2
I2S_GAIN = board.A3

print("init i2s")
audio = audiobusio.I2SOut(I2S_BCLK, I2S_LRC, I2S_DIN)

gain = digitalio.DigitalInOut(board.A3)
gain.direction = digitalio.Direction.OUTPUT
gain.value = True

#wav_file = "wav/StreetChicken.wav"
#wav_file = "/sd/music/StreetChicken.wav"
wav_file = "/sd/music/xzl2.wav"
stats = os.stat(wav_file)
filesize = stats[6]
print("filesize of %s is %d" % (wav_file, filesize))

times = 0
while True:
    times = times + 1
    print("times is %d" % times)
    count=0
    print("play wav")
    wav = audiocore.WaveFile(wav_file)
    print("Playing wav file!")
    audio.play(wav)
    while audio.playing:
        print(count, end=" ")
        time.sleep(1)
        count=count+1
    print("")

print("Done!")
